package android.pot.com.smartcar;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.pot.com.smartcar.application.MyApplication;
import android.pot.com.smartcar.map.MapRouteUtil;
import android.pot.com.smartcar.map.MyDrivingRouteOverlay;
import android.pot.com.smartcar.map.routeplan.RoutePlan;
import android.pot.com.smartcar.map.routeplan.RouteResultManage;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRouteResult;


/**
 * Created by zhaoshilu on 2017/9/2.
 */

public class BaiduMapActivity extends Activity implements RouteResultManage, View.OnClickListener, BaiduMap.OnMapLoadedCallback {

    private MapView mMapView;

    private int zoomSize = 14;//初始层级


    private BaiduMap mBaiduMap;

    private Context context;

    //定位相关
    private LocationClient mLocationClient;

    private MyLocationListener myLocationListener;

    private boolean isFirstIn = true;

    private double mLatitude;

    private double mLongtitude;
    //自定义定位图标
    private BitmapDescriptor mIconLocation;

    //覆盖物相关
    private BitmapDescriptor mMarker;


    private LatLng mlatLng;//定位  我的位置

    private LatLng shopLatLng;//商铺地址

    private String lng;

    private String lat;

    private String markAddress;

    private String markName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        context = this;
        setContentView(R.layout.activity_baidu_map);
        initView();
//        initMarker();
        initLocation();
        //初始化定位
        addShopOverlay();


        addListener();

    }


    protected void initView() {

        mMapView = (MapView) findViewById(R.id.id_bmapView);
        mBaiduMap = mMapView.getMap();

        Bundle bundle = getIntent().getExtras();
        String remark = bundle.getString("latLng");
        markAddress = bundle.getString("address");
        markName = bundle.getString("name");
//        String remark = "108.925884,34.305431";

        if (TextUtils.isEmpty(remark)) {
            remark = "108.95346,34.265725";//钟楼
        }
        if (remark.contains(",")) {
            String[] lbs = remark.split(",");
            lng = lbs[0];
            lat = lbs[1];
            shopLatLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
        } else {
            shopLatLng = new LatLng(0, 0);
        }

        MapStatus ms = new MapStatus.Builder().target(shopLatLng).zoom(zoomSize).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
        mBaiduMap.setOnMapLoadedCallback(this);


    }


    /**
     * 添加覆盖物
     */
    private void addShopOverlay() {
//        mBaiduMap.clear();
        //marker布局
        View view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.marker_view, null);
        TextView title = (TextView) view.findViewById(R.id.tv_marker_title);
        TextView site = (TextView) view.findViewById(R.id.tv_shop_site);
        title.setText(markName);
        site.setText(markAddress);
        //marker经纬度

        //marker图标
        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(view);
        OverlayOptions ops = new MarkerOptions().position(shopLatLng).icon(markerIcon).zIndex(5);
        mBaiduMap.addOverlay(ops);
    }

    protected void addListener() {


        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.iv_center).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                centerToMyLocation();
            }
        });

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                MapRouteUtil.showMapByDriveDialog(BaiduMapActivity.this, markAddress, shopLatLng);

                return true;
            }
        });

    }

    @Override
    public void routeResultFail() {
        Toast.makeText(this, "fail", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void routeResultSuccess(DrivingRouteResult result) {
        DrivingRouteLine route = result.getRouteLines().get(0); //获取路线
        MyDrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);


        MapStatus ms = new MapStatus.Builder().target(shopLatLng).zoom(zoomSize).build();

        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));

        overlay.setData(result.getRouteLines().get(0));//overLay 为在地图上的路径 ，这里为它设置数据
        overlay.addToMap();  //添加到地图
        overlay.zoomToSpan();


    }


    @Override
    public void onClick(View v) {

    }

    /**
     * 移动到指定点
     */
    private void animToLatLng(double latitude, double longtitude) {
        LatLng latLng = new LatLng(latitude, longtitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.animateMapStatus(msu);
    }

    protected void initData() {


    }

    @Override
    public void onMapLoaded() {
        MapStatus ms = new MapStatus.Builder().zoom(zoomSize + 1).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
    }


    private void initMarker() {
        mMarker = BitmapDescriptorFactory.fromResource(R.drawable.img_map_icon);

        //定义Maker坐标点
        LatLng point = new LatLng(Double.parseDouble(lat),Double.parseDouble(lng) );

//构建Marker图标

        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.img_map_icon);

//构建MarkerOption，用于在地图上添加Marker

        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);

//在地图上添加Marker，并显示

        mBaiduMap.addOverlay(option);

    }

    private void initLocation() {
        mLocationClient = new LocationClient(this);
        myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setScanSpan(1000);
        mLocationClient.setLocOption(option);
        mIconLocation = BitmapDescriptorFactory.fromResource(R.drawable.xuanzhong);
    }


    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mMapView = null;
        mBaiduMap.setMyLocationEnabled(false);
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执
        // 行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //开启定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();

        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //停止定位
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }


    /**
     * 定位到我的位置
     */
    private void centerToMyLocation() {

        LatLng latLng = new LatLng(mLatitude, mLongtitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.animateMapStatus(msu);
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            MyLocationData data = new MyLocationData.Builder()//
                    .accuracy(bdLocation.getRadius())//
                    .latitude(bdLocation.getLatitude())//
                    .longitude(bdLocation.getLongitude()).build();
            mBaiduMap.setMyLocationData(data);
            //设置自定义图标
//            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,true,mIconLocation);
//            mBaiduMap.setMyLocationConfiguration(config);
            //更新经纬度
            mLatitude = bdLocation.getLatitude();
            mLongtitude = bdLocation.getLongitude();
            if (isFirstIn) {
                mlatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(mlatLng);
//                mBaiduMap.animateMapStatus(msu);
                RoutePlan routePlan = new RoutePlan(BaiduMapActivity.this, mlatLng, shopLatLng);
                routePlan.search();


                isFirstIn = false;

            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }
}

